package com.rao.security;

import com.rao.security.entity.SysUser;
import com.rao.security.mapper.SysUserMapper;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Security 数据库 用户和角色 权限控制 案例启动类
 *
 * @author raos
 * @emil 991207823@qq.com
 * @date 2021/09/06 22:21
 */
@MapperScan(value = "com.rao.security.mapper")
@SpringBootApplication
public class UserRoleSourceApp {

    public static void main(String[] args) {
        SpringApplication.run(UserRoleSourceApp.class, args);
    }

    @Autowired
    SysUserMapper userMapper;

//    @PostConstruct // 初始化数据开启
    public void jdbcInit() {

        Date curDate = new Date();
        PasswordEncoder encoder = new BCryptPasswordEncoder();

        List<GrantedAuthority> list = new ArrayList<>();
        //参数角色名称，需要以"ROLE_"开头， 后面加上自定义的角色名称
        GrantedAuthority authority = new SimpleGrantedAuthority("ROLE_" + "USER");
        list.add(authority);

        SysUser user = new SysUser("zs", encoder.encode("123"), "张三",
                true, true, true, true, curDate, curDate, list);
        userMapper.insertSysUser(user);

        list = new ArrayList<>();
        authority = new SimpleGrantedAuthority("ROLE_" + "READ");
        list.add(authority);
        user = new SysUser("lisi", encoder.encode("456"), "李四",
                true, true, true, true, curDate, curDate, list);
        userMapper.insertSysUser(user);

        List<GrantedAuthority> list2 = new ArrayList<>();
        GrantedAuthority authority2 = new SimpleGrantedAuthority("ROLE_" + "ADMIN");
        GrantedAuthority authority3 = new SimpleGrantedAuthority("ROLE_" + "USER");
        list.add(authority2);
        list.add(authority3);

        SysUser user2 = new SysUser("admin", encoder.encode("admin"), "管理员",
                true, true, true, true, curDate, curDate, list2);
        userMapper.insertSysUser(user2);
    }

}
